package br.com.toscano.contpedido.view.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import br.com.toscano.contpedido.constant.ConstantesMensagem;
import br.gov.frameworkdemoiselle.annotation.Name;
import br.gov.frameworkdemoiselle.util.Beans;
import br.gov.frameworkdemoiselle.util.ResourceBundle;

@FacesValidator(EmailValidator.VALIDATOR_ID)
@Name(EmailValidator.VALIDATOR_ID)
public class EmailValidator implements Validator {

    public static final String VALIDATOR_ID = "emailValidator";
    
    @Override
    public void validate(FacesContext facesContext, UIComponent component, 
        Object value) throws ValidatorException {
    	if (value != null){ 
            String input = (String) value;
            Pattern p = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$");
            //Pattern p = Pattern.compile("^(?:[a-zA-Z0-9_'^&amp;/+-])+(?:\\.(?:[a-zA-Z0-9_'^&amp;/+-])+)*@(?:(?:\\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\]?)|(?:[a-zA-Z0-9-]+\\.)+(?:[a-zA-Z]){2,}\\.?)$"); //(".+@.+\\.[a-z]+");
            Matcher m = p.matcher(input);
            
            if (!m.find()){
            	throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, 
        				Beans.getReference(ResourceBundle.class).getString(ConstantesMensagem.MSG_ERRO_EMAIL_INVALIDO), null));
            }    	
    		
    	}
    }
    
}